package fm.controller;

import com.alibaba.fastjson.JSON;
import fm.cache.SegmentNumberCache;
import fm.entity.*;
import fm.entityEnum.ShareTypeEnum;
import fm.exception.BizException;
import fm.service.ActivityService;
import fm.service.PublicNumberService;
import fm.service.UserService;
import fm.util.CommonUtils;
import fm.util.Constant;
import fm.util.JsApiSignUtil;
import fm.util.WechatUtils;
import fm.web.MediaTypes;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：fm.controller.FlowMarketDataController
 * 创建者： CM .
 * 创建时间：2016/3/10
 */
@Controller
@RequestMapping("/market/flow")
public class FlowMarketDataController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowMarketDataController.class);

    @Autowired
    private ActivityService activityService;

    @Autowired
    UserService userService;

    /**
     * 活动参与页面数据获取接口
     *
     * @param modelMap
     * @param activityId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String index(ModelMap modelMap, @PathVariable(value = "id") Long activityId) throws Exception {
        modelMap.clear();
        try {
            Activity activity = activityService.getById(activityId);
            WxUser user = getCurrentUser();
            HashMap<String, Object> data = new HashMap<>();
            data.put("logo", activity.getLogoUrl());
            data.put("title", activity.getTitle());
            data.put("rule", activity.getRule());

            //是否参与过活动
            List<RecorderParticipation> userRecorders = activityService.getUserRecorders(user, activity);
            data.put("hasJoined", userRecorders.size() > 0);
            //已经参与过
            if (CollectionUtils.isNotEmpty(userRecorders)) {
                data.put("avatar", user.getHeadimgurl());
                if (!CommonUtils.isEmpty(userRecorders.get(0).getFlow())) {
                    data.put("prize", userRecorders.get(0).getFlow().getCapacity() + "M");
                }
                long currentTime = System.currentTimeMillis() / 1000;
                long createTime = userRecorders.get(0).getCreateTime().getTime() / 1000;
                long restTime = 3600 + (createTime - currentTime);
                data.put("available", "60");
                data.put("remainTime", restTime);
                data.put("exchangeStatus", userRecorders.get(0).getExchangeStatus().getDesc());
            }

            data.put("list", activityService.getWinnerList(activity));

            modelMap.put("data", data);
            this.success(modelMap);
        } catch (BizException ex) {
            LOGGER.error("activity index occur error:", ex);
            this.failed(modelMap);
        }
        String result = JSON.toJSONString(modelMap);
        return result;
    }

    /**
     * 抽奖
     *
     * @param modelMap
     * @param activityId
     * @param tel
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/{id}/lottery", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String lottery(ModelMap modelMap,
                          @PathVariable(value = "id") Long activityId,
                          @RequestParam String tel) throws Exception {
        modelMap.clear();
        try {
            WxUser user = getCurrentUser();

            Activity activity = activityService.getById(activityId);
            if (CommonUtils.isEmpty(activity)) {
                throw new BizException("活动不存在,获取已经过期咯！!");
            }

            //判断是否已经参与过
            List<RecorderParticipation> userRecorders = activityService.getUserRecorders(user, activity);
            if (CollectionUtils.isNotEmpty(userRecorders) && userRecorders.size() > 0) {
                throw new BizException("本次活动期间内，每个用户只能参与一次哦！");
            }
            //校验奖品剩余数量
            if (activity.getRemainCount() <= 0) {
                throw new BizException("奖品已经被抢光了!");
            }
            //获取奖品列表 根据运营商
            //获取运营商
            SegmentNumber segmentNumber = SegmentNumberCache.getSegmentNumber(tel);
            if (CommonUtils.isEmpty(segmentNumber)) {
//                号段不存在 直接失败
                activityService.addRecorder(null, activity, user, false, tel);

                throw new BizException("很遗憾，没有抢到！");
            }

            List<ActivityFlow> flows = activityService.getActivityFlows(activity, segmentNumber.getCarrier());
            if (CollectionUtils.isEmpty(flows)) {
                throw new RuntimeException("活动奖品没有配置，无法抽奖！");
            }
            //计算获取的奖品
            ActivityFlow prize = activityService.getPrize(flows);
            //中奖后更新手机号码
            if (StringUtils.isEmpty(user.getTelephone())) {
                user.setTelephone(tel);
                userService.saveOrUpdate(user);
            }
            //添加中奖纪录
            RecorderParticipation recorder = activityService.addRecorder(prize.getFlow(), activity, user, true, tel);

            HashMap<String, Object> data = new HashMap<>();
            modelMap.put("msg", "");
            data.put("prize", prize.getFlow().getCapacity() + "M");
            data.put("hasWin", Boolean.valueOf(true));
            data.put("available", 60);
            Thread.sleep(300);
            long currentTime = System.currentTimeMillis() / 1000;
            long createTime = recorder.getCreateTime().getTime() / 1000;
            data.put("remainTime", createTime - currentTime + (60 * 60));

            data.put("logo", activity.getLogoUrl());
            modelMap.put("data", data);
            data.put("rule", activity.getRule());
            data.put("title", activity.getTitle());
            data.put("list", activityService.getWinnerList(activity));

            this.success(modelMap);
        } catch (BizException ex) {
            LOGGER.error("activity index occur error:", ex);
            this.failed(modelMap, ex);
        }
        return JSON.toJSONString(modelMap);
    }

    @ResponseBody
    @RequestMapping(value = "/exchange/{id}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String doExchange(ModelMap modelMap,
                             @PathVariable(value = "id") Long activityId) {
        modelMap.clear();
        try {
            if (CommonUtils.isEmpty(activityId)) {
                throw new BizException("活动信息不存在!");
            }

            Activity activity = activityService.getById(activityId);
            if (CommonUtils.isEmpty(activity)) {
                throw new BizException("活动信息不存在!");

            } else {
                HashMap<String, Object> data = new HashMap<>();
                data.put("logo", activity.getLogoUrl());
                data.put("title", activity.getTitle());
                data.put("rule", activity.getRule());
                modelMap.put("data", data);
                modelMap.put("msg", "");
                WxUser user = getCurrentUser();
                ShareConfig config = activityService.getShareConfigBuyUser(user);
                if (!CommonUtils.isEmpty(config)) {
                    //配置过分享，并且是从配置页面跳转过来
                    List<RecorderParticipation> recorderParticipation = activityService.getUserRecorders(user, activity);
                    RecorderParticipation recorder = null;
                    if (CollectionUtils.isNotEmpty(recorderParticipation)) {
                        recorder = recorderParticipation.get(0);
                        data.put("flowSize", recorder.getFlow().getCapacity());
                    }
                }
                this.success(modelMap);
            }
        } catch (BizException ex) {
            LOGGER.error("exchange page data request occur error:", ex);
            this.failed(modelMap, ex);
        } catch (Exception e) {
            LOGGER.error("exchange page data request occur error:", e);
            this.failed(modelMap, "服务器发生错误，数据请求失败！");
        }

        return JSON.toJSONString(modelMap);
    }

    @ResponseBody
    @RequestMapping(value = "/share/config/{id}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String doShareConfig(ModelMap modelMap,
                                @PathVariable(value = "id") Long activityId,
                                @RequestParam String value, @RequestParam String type) {
        try {
            if (CommonUtils.isEmpty(value) || CommonUtils.isEmpty(type)) {
                throw new BizException("参数缺失，请求失败!");
            }
            ShareConfig config = new ShareConfig();
            if (type.equals(ShareTypeEnum.LINK.toString())) {
                config.setDownloadLink(value);
            } else if (type.equals(ShareTypeEnum.TD_CODE.toString())) {
                config.setTdCode(value);
            } else {
                throw new BizException("配置错误！");
            }
            config.setShareType(ShareTypeEnum.valueOf(type));
            WxUser user = getCurrentUser();
            config.setWxUser(user);
            LOGGER.debug("config share :{},user :{}", JSON.toJSONString(config), user.getOpenid());
            Long id = activityService.addShareConfig(config);
            modelMap.put("id", id);
            this.success(modelMap);
        } catch (BizException ex) {
            this.failed(modelMap, ex);
        } catch (Exception ex) {
            this.failed(modelMap, "服务器发生错误！");
        }

        return JSON.toJSONString(modelMap);
    }

    @Autowired
    private PublicNumberService publicNumberService;

    @RequestMapping(value = "/exchange/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public String exchange(ModelMap modelMap,
                           @PathVariable(value = "id") Long activityId, @RequestParam(value = "sst", required = false) String sst,
                           HttpServletRequest request) throws Exception {
        Activity activity = activityService.getById(activityId);
        WxUser user = getCurrentUser();
        PublicNumber publicNumber = getCurrentPublicNumber();

        String accessToken = WechatUtils.getBaseAccessToken(publicNumber.getAppid(), publicNumber.getAppsecret(), Constant.GRANT_TYPE_CLIENT_CREDENTIAL, request);
        String ticket = WechatUtils.getJsApiTicket(request, accessToken, publicNumber.getUuid());
        Map sign = JsApiSignUtil.sign(ticket, request.getRequestURL().toString() + "?" + request.getQueryString());

        modelMap.put("appid", publicNumber.getAppid());
        modelMap.put("logo", activity.getLogoUrl());
        modelMap.put("title", activity.getTitle());
        modelMap.put("url", activity.getLink() + "&shareUserId=" + user.getId());
        modelMap.put("desc", activity.getDescription());
        modelMap.put("sign", sign);
        modelMap.put("id", activity.getId());
        modelMap.put("uuid", publicNumber.getUuid());
        modelMap.put("sst", sst);

        return "/market/exchange";
    }


}
